package com.king.juc.n8.jucdemo.aqs;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * 自定义锁
 *
 * @author king
 * @date 2020/12/12 21:04
 */
public class MyLock implements Lock {

    private MySync sync = new MySync();

    /**
     * 加锁(不成功会进入等待队列)
     */
    @Override
    public void lock() {
        sync.acquire(1);
    }

    /**
     * 加锁, 可打断
     *
     * @throws InterruptedException
     */
    @Override
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    /**
     * 尝试加锁(一次)
     *
     * @return
     */
    @Override
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    /**
     * 尝试加锁, 带超时
     *
     * @param time 超时时间
     * @param unit 时间单位
     * @return
     * @throws InterruptedException
     */
    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1, unit.toNanos(time));
    }

    /**
     * 解锁
     */
    @Override
    public void unlock() {
        sync.release(0);
    }

    /**
     * 创建条件变量
     *
     * @return
     */
    @Override
    public Condition newCondition() {
        return sync.newCondition();
    }
}
